package com.dnjn.happiness.biz.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dnjn.happiness.biz.domain.Training;
import com.dnjn.happiness.biz.domain.TrainingRecord;
import com.dnjn.happiness.biz.domain.TrainingRecordVO;
import com.dnjn.happiness.biz.domain.TrainingVO;
import com.dnjn.happiness.biz.domain.vo.StatisticalAnalysisAppriseVO;
import com.dnjn.happiness.biz.domain.vo.StatisticalAnalysisVO;
import com.dnjn.happiness.biz.mapper.TrainingMapper;
import com.dnjn.happiness.biz.mapper.TrainingRecordMapper;
import com.dnjn.happiness.biz.service.ITrainingService;
import com.dnjn.happiness.biz.service.ITrainingTagsService;
import com.dnjn.happiness.common.amqp.AmqpSender;
import com.dnjn.happiness.common.core.constant.HappyConstants;
import com.dnjn.happiness.common.core.constant.SecurityConstants;
import com.dnjn.happiness.common.core.domain.R;
import com.dnjn.happiness.common.core.model.SysJobVO;
import com.dnjn.happiness.common.core.utils.StringUtils;
import com.dnjn.happiness.common.core.web.domain.AjaxResult;
import com.dnjn.happiness.common.security.utils.SecurityUtils;
import com.dnjn.happiness.common.core.score.vo.HappyTraining;
import com.dnjn.happiness.common.core.score.vo.HappyVO;
import com.dnjn.happiness.job.api.RemoteJobService;
import com.dnjn.happiness.system.api.domain.SysUser;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 发起培训Service业务层处理
 *
 * @author amber
 * @date 2023-10-11
 */
@Service
public class TrainingServiceImpl extends ServiceImpl<TrainingMapper, Training> implements ITrainingService {
    /**
     * 状态标识符
     */
    public static final String READY = "READY";
    public static final String PROCESSING = "PROCESSING";
    public static final String FINISHED = "FINISHED";
    @Autowired
    private TrainingMapper trainingMapper;
    @Autowired
    private RemoteJobService jobService;
    @Autowired
    private ITrainingTagsService trainingTagsService;
    @Value("${training.issuedWhetherAttend}")
    private Boolean issuedWhetherAttend;

    
    /**
     * 查询发起培训列表
     *
     * @param training 发起培训
     * @return 发起培训
     */
//    @Override
//    public List<Training> selectTrainingList(Training training) {
//        return trainingMapper.selectTrainingList(training);
//    }


    @Autowired
    private TrainingRecordMapper trainingRecordMapper;

    /**
     * 查询发起培训
     *
     * @param trainingId 发起培训主键
     * @return 发起培训
     */
    @Override
    public Training selectTrainingByTrainingId(String trainingId) {
        return trainingMapper.selectTrainingByTrainingId(trainingId);
    }


    /**
     * 新增发起培训
     *
     * @param training 发起培训
     * @return 结果
     */
    @Override
    @Transactional
    public int insertTraining(TrainingVO training) {
        training.setCreateTime(LocalDateTime.now());//培训创建时间
        SysUser user = SecurityUtils.getLoginUser().getUser();//获取当前登录用户作为发起者
        training.setInitiator(String.valueOf(user.getUserId()));//给发起者赋值
        //判断开始时间 是否在今天之前
        if (training.getDateStart().isBefore(LocalDateTime.now())) {
            training.setTrainingStatus(PROCESSING);
        } else {
            training.setTrainingStatus(READY);
        }
        int count = trainingMapper.insert(training);


        //这里开始添加培训记录

        List<Long> userIds = training.getUserIds();
        if (!CollectionUtils.isEmpty(userIds) && count > 0) { for (Long userId : training.getUserIds()) {
            TrainingRecord trainingRecord = new TrainingRecord();
            trainingRecord.setTrainingId(training.getTrainingId());
            trainingRecord.setUserId(userId);
            String sued = training.getSued();
            if ("Y".equals(sued) && issuedWhetherAttend){
                trainingRecord.setTrainingRecordStatus("Y");
            }else {
                trainingRecord.setTrainingRecordStatus("N");
            }
            trainingRecordMapper.insert(trainingRecord);

            // todo training
            HappyVO happyVO = new HappyVO();
            happyVO.setUserId(userId);
            HappyTraining happyTraining = new HappyTraining();
            happyTraining.setJoin(1);
            happyVO.setRtype(HappyConstants.EMO_USER_RTYPE_TRAINING);
            happyVO.setTraining(happyTraining);
            AmqpSender.sendArgs(happyVO);

        }
        }

        return count;
    }


    /**
     * 修改发起培训
     *
     * @param training 发起培训
     * @return 结果
     */
    @Override
    public int updateTraining(TrainingVO training) {
        training.setUpdateTime(LocalDateTime.now());
        //判断开始时间 是否在今天之前
        if (training.getDateStart().isBefore(LocalDateTime.now())) {
            training.setTrainingStatus(PROCESSING);
        } else {
            training.setTrainingStatus(READY);
        }
        //先修改
        int i = trainingMapper.updateById(training);
        //先把之前的指定的培训人删了
        trainingRecordMapper.delete(Wrappers.lambdaQuery(TrainingRecord.class).eq(TrainingRecord::getTrainingId, training.getTrainingId()));
        List<Long> userIds = training.getUserIds();
        if (!CollectionUtils.isEmpty(userIds) && i > 0) {
            for (Long userId : training.getUserIds()) {
                TrainingRecord trainingRecord = new TrainingRecord();
                trainingRecord.setTrainingId(training.getTrainingId());
                trainingRecord.setUserId(userId);
                String sued = training.getSued();
                if ("Y".equals(sued) && issuedWhetherAttend){
                    trainingRecord.setTrainingRecordStatus("Y");
                }else {
                    trainingRecord.setTrainingRecordStatus("N");
                }
                trainingRecordMapper.insert(trainingRecord);
            }
        }
        return i;
    }


    /**
     * 分页 条件 组合查询
     *
     * @param current
     * @param size
     * @param example
     * @return
     */
    @Override
    public Page<Training> pageCommentVo(Integer current, Integer size, Map<String, Object> example) {
        Page<Training> pageCommentVo = baseMapper.pageCommentVoByMap(new Page(current, size), example);
        return pageCommentVo;
    }



    @Override
    public int getTraingRecordNotJoin(Long userId,String time) {

        return trainingMapper.getTraingRecordNotJoin(userId,time);
    }

    @Override
    public void startTraingTime(Training domain) throws Exception {
        String dayOfYear = String.valueOf(domain.getDateStart().getYear());//年
        String month = String.valueOf(domain.getDateStart().getMonthValue());//月
        // 今天是周几（返回的是个枚举类型，需要再getValue()）
        String dayofWeek = String.valueOf(domain.getDateStart().getDayOfWeek().getValue());//周几
        String dayofMonth = String.valueOf(domain.getDateStart().getDayOfMonth());//几号
        String hour = String.valueOf(domain.getDateStart().getHour());//小时
        String minute = String.valueOf(domain.getDateStart().getMinute());//分钟
        String second = String.valueOf(domain.getDateStart().getSecond());//秒
//        String s = String.valueOf(dayOfYear);

//        String cronStr = "0" + " " + s2 + " " + s1 + " * * ?";
        String cronStr = second + " " + minute + " " + hour + " " + dayofMonth + " " + month + " " + "?" + " " + dayOfYear;
        SysJobVO job = new SysJobVO();
        job.setJobGroup("surveyHandler");
        job.setJobName("surveyHandler" + domain.getTrainingId().toString());
        job.setCronExpression(cronStr);
        job.setInvokeTarget("surveyHandler.theTraingToStart('" + domain.getTrainingId().toString() + "')");
//            job.setInvokeTarget("workforceTask.handleWorkforceshift");
        job.setCreateBy(SecurityUtils.getUsername());
        job.setMisfirePolicy("3");
        job.setStatus("0");
        AjaxResult result = jobService.insertJob(job, SecurityConstants.INNER);

        job.setInvokeTarget("surveyHandler.theTraingToStart('" + domain.getTrainingId().toString() + "','" + job.getJobId().toString() + "' )");
        R r = jobService.updateJob(job, SecurityConstants.INNER);
        SysJobVO newJob = new SysJobVO();
        R<SysJobVO> resultJob = jobService.getInfoById(job.getJobId(), SecurityConstants.INNER);
        if (StringUtils.isNotNull(resultJob) && StringUtils.isNotNull(resultJob.getData())) {
            newJob = resultJob.getData();
        }
        newJob.setStatus("0");
        R r1 = jobService.changeStatusApi(newJob, SecurityConstants.INNER);
    }

    @Override
    public void endTraingTime(Training domain) throws Exception {
        String dayOfYear = String.valueOf(domain.getDateEnd().getYear());//年
        String month = String.valueOf(domain.getDateEnd().getMonthValue());//月
        // 今天是周几（返回的是个枚举类型，需要再getValue()）
        String dayofWeek = String.valueOf(domain.getDateEnd().getDayOfWeek().getValue());//周几
        String dayofMonth = String.valueOf(domain.getDateEnd().getDayOfMonth());//几号
        String hour = String.valueOf(domain.getDateEnd().getHour());//小时
        String minute = String.valueOf(domain.getDateEnd().getMinute());//分钟
        String second = String.valueOf(domain.getDateEnd().getSecond());//秒
//        String s = String.valueOf(dayOfYear);

//        String cronStr = "0" + " " + s2 + " " + s1 + " * * ?";
        String cronStr = second + " " + minute + " " + hour + " " + dayofMonth + " " + month + " " + "?" + " " + dayOfYear;
        SysJobVO job = new SysJobVO();
        job.setJobGroup("surveyHandler");
        job.setJobName("surveyHandler" + domain.getTrainingId().toString());
        job.setCronExpression(cronStr);
        job.setInvokeTarget("surveyHandler.theTraingToEnd('" + domain.getTrainingId().toString() + "')");
//            job.setInvokeTarget("workforceTask.handleWorkforceshift");
        job.setCreateBy(SecurityUtils.getUsername());
        job.setMisfirePolicy("3");
        job.setStatus("0");
        AjaxResult result = jobService.insertJob(job, SecurityConstants.INNER);

        job.setInvokeTarget("surveyHandler.theTraingToEnd('" + domain.getTrainingId().toString() + "','" + job.getJobId().toString() + "' )");
        R r = jobService.updateJob(job, SecurityConstants.INNER);
        SysJobVO newJob = new SysJobVO();
        R<SysJobVO> resultJob = jobService.getInfoById(job.getJobId(), SecurityConstants.INNER);
        if (StringUtils.isNotNull(resultJob) && StringUtils.isNotNull(resultJob.getData())) {
            newJob = resultJob.getData();
        }
        newJob.setStatus("0");
        R r1 = jobService.changeStatusApi(newJob, SecurityConstants.INNER);
    }

    @Override
    public Page<StatisticalAnalysisVO> selectStatisticalAnalysisTrainingMap(Map<String, String> map, Page<Object> happiness_score) {
        return baseMapper.selectStatisticalAnalysisTrainingMap(map,happiness_score);
    }

    @Override
    public Page<StatisticalAnalysisVO> selectStatisticalAnalysisTrainingList(StatisticalAnalysisAppriseVO voList, Page<Object> happiness_score) {
        return baseMapper.selectStatisticalAnalysisTrainingList(voList,happiness_score);
    }

    @Override
    public List<StatisticalAnalysisVO> selectStatisticalAnalysisTrainingList1(StatisticalAnalysisAppriseVO vo) {
        return baseMapper.selectStatisticalAnalysisTrainingList1(vo);
    }

    @Override
    public int getTraingRecordYesJoin(Long userId,String time) {
        return baseMapper.getY(userId,time);
    }
    @Override
    public Page<StatisticalAnalysisVO> selectStatisticalAnalysisTraining(String label, String symbol, Page page) {
        return baseMapper.selectStatisticalAnalysisTraining(label, symbol, page);
    }

    @Override
    public Page<Training> listQueryByMy(TrainingRecordVO domain, Page page) {
        return trainingMapper.listQueryByMy(domain, page);
    }

    @Override
    public Page<Training> listQueryByMyInTo(Long userid, String trainingRecordStatus, Page page) {
        return trainingMapper.listQueryByMyInTo(userid, trainingRecordStatus, page);
    }

    @Override
    public Page<Training> listQueryByMy1(Long initiator, Page page) {

        return trainingMapper.listQueryByMy1(initiator, page);
    }
}
